package com.un.ebs.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.product.domain.ProductClassAttrValue;
import com.un.ebs.product.dto.ProductClassAttrValueAddDto;
import com.un.ebs.product.dto.ProductClassAttrValueUpdateDto;
import com.un.ebs.product.enums.ProductValueExpressionTypeEnum;
import com.un.ebs.product.mapper.ProductClassAttrValueMapper;
import com.un.ebs.product.service.ProductClassAttrValueService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liubo
 * @since 2019-09-16
 */
@Service
public class ProductClassAttrValueServiceImpl extends ServiceImpl<ProductClassAttrValueMapper, ProductClassAttrValue> implements ProductClassAttrValueService {

    @CacheEvict(cacheNames = {"product_class_attr", "spu_attr_value"}, allEntries = true)
    @Override
    public void add(ProductClassAttrValueAddDto req) {
        ProductClassAttrValue obj = new ProductClassAttrValue();
        obj.setClassAttrId(req.getClassAttrId());
        obj.setValue(req.getValue());
        obj.setCode(req.getCode());
        obj.setIsDelete(false);
        obj.setSort(getBaseMapper().maxSort());
        if (!StringUtils.isNullOrEmpty(req.getExpression())) {
            obj.setExpressionType(ProductValueExpressionTypeEnum.TimePeriod);
            obj.setExpression(req.getExpression());
        } else {
            obj.setExpressionType(ProductValueExpressionTypeEnum.Default);
        }
        obj.insert();
    }

    @CacheEvict(cacheNames = {"product_class_attr", "spu_attr_value"}, allEntries = true)
    @Override
    public void update(ProductClassAttrValueUpdateDto req) {
        ProductClassAttrValue obj = getById(req.getId());
        obj.setClassAttrId(req.getClassAttrId());
        obj.setValue(req.getValue());
        obj.setCode(req.getCode());
        if (!StringUtils.isNullOrEmpty(req.getExpression())) {
            obj.setExpressionType(ProductValueExpressionTypeEnum.TimePeriod);
            obj.setExpression(req.getExpression());
        } else {
            obj.setExpressionType(ProductValueExpressionTypeEnum.Default);
        }
        obj.updateById();
    }

    @Override
    public ProductClassAttrValue queryById(String id) {
        return getBaseMapper().selectById(id);
    }

    @CacheEvict(cacheNames = {"product_class_attr", "spu_attr_value"}, allEntries = true)
    @Override
    public void delete(String id) {
        getBaseMapper().deleteById(id);
    }

    @CacheEvict(cacheNames = {"product_class_attr", "spu_attr_value"}, allEntries = true)
    @Override
    public void changeSort(String id, int index) {
        ProductClassAttrValue obj = getById(id);
        obj.setSort(index);
        getBaseMapper().updateById(obj);
    }

}